package beat

import (
	"encoding/json"
	"log"
	"os"
	"time"
	"xiaoniu-task/internal/config"
	"xiaoniu-task/pkg/util"
)

var stop = false

var heartBeatLogger *log.Logger
var curLogFile *os.File

func init() {
	logFile, err := os.OpenFile("heartbeat.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)

	if err != nil {
		log.Fatalln("心跳日志打开失败！")
	}
	curLogFile = logFile
	heartBeatLogger = log.New(curLogFile, "[本地心跳]", log.LstdFlags|log.Lshortfile|log.Ldate|log.Ltime)

}

// StartHeartBeatJob 间隔30s向服务端发送心跳请求
func StartHeartBeatJob() {
	for {
		if stop {
			// 停止发送心跳请求
			break
		}
		go sendHeartBeat()
		time.Sleep(time.Second * 30)
	}
}

func sendHeartBeat() {
	localIp := util.GetLocalIp()
	if localIp == "" {
		return
	}
	if config.ClientRation.Port == "" {
		return
	}
	if config.ClientRation.AdminServer == "" {
		return
	}
	if config.ClientRation.ExecutorName == "" {
		return
	}

	var body = make(map[string]interface{}, 3)
	body["ip"] = localIp
	body["port"] = config.ClientRation.Port
	body["name"] = config.ClientRation.ExecutorName
	// 注册请求
	body["type"] = 1
	res, err := util.PostJson(config.ClientRation.AdminServer+"/api/client/heartBeat", body)
	marshal, _ := json.Marshal(res)
	heartBeatLogger.Println("Send HeartBeat to Admin Server: ", string(marshal), err)
}

// StopHeartBeat 调用此函数使得当前客户端不再向服务端发送心跳请求
func StopHeartBeat() {
	go RemoveSelfFromServer()
	stop = true
}

// RemoveSelfFromServer 从服务器取消当前执行器客户端的注册
func RemoveSelfFromServer() {
	localIp := util.GetLocalIp()
	if localIp == "" {
		return
	}
	if config.ClientRation.Port == "" {
		return
	}
	if config.ClientRation.AdminServer == "" {
		return
	}
	if config.ClientRation.ExecutorName == "" {
		return
	}

	var body = make(map[string]interface{}, 3)
	body["ip"] = localIp
	body["port"] = config.ClientRation.Port
	body["name"] = config.ClientRation.ExecutorName
	// 取消注册请求
	body["type"] = 2
	res, err := util.PostJson(config.ClientRation.AdminServer+"/api/client/heartBeat", body)
	marshal, _ := json.Marshal(res)
	heartBeatLogger.Println("Send DisRegister Request to Admin Server: ", string(marshal), err)

	curLogFile.Close()
}
